package com.etogc.groupchat.login.biz;

import android.app.Activity;
import android.content.Context;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

import com.etogc.groupchat.login.ui.LoginActivity;
import com.etogc.http.ReqDataHandler;
import com.etogc.http.ReqErrorHandler;
import com.etogc.http.VolleyHttpUtil;
import com.etogc.groupchat.main.MainActivity;
import com.etogc.groupchat.common.CommonSp;
import com.etogc.util.GcUrl;
import com.etogc.util.ImageUtils;
import com.etogc.util.IntentHelper;
import com.etogc.util.MD5Util;
import com.etogc.util.StringUtil;
import com.etogc.util.YcToastHelper;
import com.etogc.view.LoadDialog;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.UserInfo;

/**
 * Created by ZeroVoid on 2018-2-24.
 */

public class LoginHttpBiz {

    public static void getSms(final Context ctx, String tel, VolleyHttpUtil.ResponseCallBack callback) {
        if (TextUtils.isEmpty(tel)) {
            return;
        }
        LoadDialog.show(ctx);
        VolleyHttpUtil.getInstance().getWithCallback(GcUrl.SMS + tel
                , callback);

    }

    public static void getSms(final Context ctx, String tel) {
        if (TextUtils.isEmpty(tel)) {
            return;
        }
        LoadDialog.show(ctx);
        VolleyHttpUtil.getInstance().getWithCallback(GcUrl.SMS + tel
                , new VolleyHttpUtil.ResponseCallBack() {
                    @Override
                    public void handleResponse(JSONObject response, int errCode) {
                        LoadDialog.dismiss(ctx);
                        boolean isSuccess = ReqErrorHandler.getInstance().isSuccess(response, true);
                        if (isSuccess) {
                            YcToastHelper.getInstance()._toast("请求验证码成功");
                        }
                    }
                });

    }


    public static void reg(final Activity act, String tel, String pwd, String verify) {
        LoadDialog.show(act);
        HashMap<String, Object> map = new HashMap<>();
        map.put("tel", tel);
        map.put("password", pwd);
        map.put("code", verify);
        VolleyHttpUtil.getInstance().postWithCallback(GcUrl.REG, map, new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject response, int errCode) {
                LoadDialog.dismiss(act);
                boolean isSuccess = ReqErrorHandler.getInstance().isSuccess(response, true);
                if (isSuccess) {
                    IntentHelper.finish(act);
                    YcToastHelper.getInstance()._toast("注册成功");
                }
            }
        });
    }

    public static void bind(final Activity act, String tel, String pwd, String code) {
        LoadDialog.show(act);
        HashMap<String, Object> map = new HashMap<>();
        map.put("phone", tel);
        map.put("password", pwd);
        VolleyHttpUtil.getInstance().postWithCallback(GcUrl.BIND, map, new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject response, int errCode) {
                LoadDialog.dismiss(act);
                boolean isSuccess = ReqErrorHandler.getInstance().isSuccess(response, true);
                if (isSuccess) {
                    IntentHelper.finish(act);
                    YcToastHelper.getInstance()._toast("绑定成功");
                }
            }
        });
    }

    public static void reset(final Activity act, String tel, String verify, String pwd, String rePwd) {
        LoadDialog.show(act);
        HashMap<String, Object> map = new HashMap<>();
        map.put("tel", tel);
        map.put("code", verify);
        map.put("password", pwd);
        map.put("password2", rePwd);
        VolleyHttpUtil.getInstance().postWithCallback(GcUrl.RESET, map, new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject response, int errCode) {
                LoadDialog.dismiss(act);
                boolean isSuccess = ReqErrorHandler.getInstance().isSuccess(response, true);
                if (isSuccess) {
                    IntentHelper.finish(act);
                    YcToastHelper.getInstance()._toast("重置成功");
                    IntentHelper.getInstances().getIntent(act, LoginActivity.class);
                }
            }
        });
    }


    public static void login(final Activity act, final String phone, String pwd, final String loginType) {
        LoadDialog.show(act);
        HashMap<String, Object> map = new HashMap<>();
        map.put("name", phone);
        String md5Pwd = MD5Util.encrypt(pwd);
        map.put("password", pwd);
        map.put("type", "0");//0=app,1=pc
        VolleyHttpUtil.getInstance().postWithCallback(GcUrl.LOGIN, map, new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject response, int errCode) {
                LoadDialog.dismiss(act);
                boolean isOk = ReqErrorHandler.getInstance().isSuccess(response, true);
                Log.e("Biz", response.toString());
                if (isOk) {
                    YcToastHelper.getInstance()._toast("登录成功");
                    Map<String, Object> map = ReqDataHandler.getMapWithEntityNoGson(response);
                    if (map != null) {
                        String token = String.valueOf(map.get("token"));
                        VolleyHttpUtil.getInstance().setHeader("token", token);
                        String rongToken = String.valueOf(map.get("rongToken"));
                        if (!StringUtil.isBlank(rongToken)) {
                            CommonSp.setRongToken(rongToken);
                        }
                        Map<String, Object> mapUser = (Map<String, Object>) map.get("user");
                        String nickName = String.valueOf(mapUser.get("nickname"));
                        String userID = String.valueOf(mapUser.get("id"));
                        String photo = ImageUtils.getImageUrl(String.valueOf(mapUser.get("photo")));
                        CommonSp.setToken(token);
                        CommonSp.setPhone(phone);
                        CommonSp.setUserID(userID);
                        CommonSp.setNickName(nickName);
                        CommonSp.setHeadUrl(photo);
                        CommonSp.setLoginType(loginType);
                        connect_rong(act, rongToken);

                        RongIM.getInstance().refreshUserInfoCache(new UserInfo(userID, nickName, Uri.parse(photo)));
                        RongIM.getInstance().setCurrentUserInfo(new UserInfo(userID, nickName, Uri.parse(photo)));
                    }
                }
            }
        });
    }

    public static void loginWX(final Activity act, final String openId, final String name, final String iconUrl, final String type) {
        LoadDialog.show(act);
        HashMap<String, Object> map = new HashMap<>();
        map.put("open_id", openId);
        map.put("type", "0");//0=app,1=pc
        VolleyHttpUtil.getInstance().postWithCallback(GcUrl.LOGIN_WX, map, new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject response, int errCode) {
                boolean isOk = ReqErrorHandler.getInstance().isSuccess(response, true);
                Log.e("Biz", response.toString());
                if (isOk) {
                    LoadDialog.dismiss(act);
                    YcToastHelper.getInstance()._toast("登录成功");
                    CommonSp.setIsWxLogin(false);
                    Map<String, Object> map = ReqDataHandler.getMapWithEntityNoGson(response);
                    if (map != null) {
                        String token = String.valueOf(map.get("token"));
                        VolleyHttpUtil.getInstance().setHeader("token", token);
                        String rongToken = String.valueOf(map.get("rongToken"));
                        if (!StringUtil.isBlank(rongToken)) {
                            CommonSp.setRongToken(rongToken);
                        }
                        Map<String, Object> mapUser = (Map<String, Object>) map.get("user");
                        String nickName = String.valueOf(mapUser.get("nickname"));
                        String userID = String.valueOf(mapUser.get("id"));
                        String photo = ImageUtils.getImageUrl(String.valueOf(mapUser.get("photo")));
                        CommonSp.setToken(token);
                        CommonSp.setUserID(userID);
                        CommonSp.setNickName(nickName);
                        CommonSp.setHeadUrl(photo);
                        CommonSp.setLoginType(type);
                        connect_rong(act, rongToken);

                        RongIM.getInstance().refreshUserInfoCache(new UserInfo(userID, nickName, Uri.parse(photo)));
                        RongIM.getInstance().setCurrentUserInfo(new UserInfo(userID, nickName, Uri.parse(photo)));
                    }
                } else {
                    if (errCode == 501) {
                        registWx(act, openId, name, iconUrl, type);
                    }
                }
            }
        });
    }

    /**
     * 注册微信
     *
     * @param act
     * @param openId
     * @param name
     * @param photoUrl
     */
    public static void registWx(final Activity act, String openId, String name, String photoUrl, final String loginType) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("name", name);
        map.put("password", "");
        map.put("open_id", openId);
        map.put("photo", photoUrl);
        map.put("type", "0");//0=app,1=pc
        VolleyHttpUtil.getInstance().postWithCallback(GcUrl.REGISTER_WX, map, new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject response, int errCode) {
                LoadDialog.dismiss(act);
                boolean isOk = ReqErrorHandler.getInstance().isSuccess(response, true);
                Log.e("Biz", response.toString());
                if (isOk) {
                    YcToastHelper.getInstance()._toast("登录成功");
                    CommonSp.setIsWxLogin(true);
                    Map<String, Object> map = ReqDataHandler.getMapWithEntityNoGson(response);
                    if (map != null) {
                        String token = String.valueOf(map.get("token"));
                        VolleyHttpUtil.getInstance().setHeader("token", token);
                        String rongToken = String.valueOf(map.get("rongToken"));
                        if (!StringUtil.isBlank(rongToken)) {
                            CommonSp.setRongToken(rongToken);
                        }
                        Map<String, Object> mapUser = (Map<String, Object>) map.get("user");
                        String nickName = String.valueOf(mapUser.get("nickname"));
                        String userID = String.valueOf(mapUser.get("id"));
                        String photo = ImageUtils.getImageUrl(String.valueOf(mapUser.get("photo")));
                        CommonSp.setToken(token);
                        CommonSp.setUserID(userID);
                        CommonSp.setNickName(nickName);
                        CommonSp.setHeadUrl(photo);
                        RongIM.getInstance().refreshUserInfoCache(new UserInfo(userID, nickName, Uri.parse(photo)));
                        RongIM.getInstance().setCurrentUserInfo(new UserInfo(userID, nickName, Uri.parse(photo)));
                        CommonSp.setLoginType(loginType);
                        connect_rong(act, rongToken);
                    }
                }
            }
        });
    }

    public static void handleLogin() {

    }

    //获取融云的token之后,连接到融云的IM服务器
    public static void connect_rong(final Activity act, String token) {
        LoadDialog.show(act);
        RongIM.connect(token, new RongIMClient.ConnectCallback() {

            @Override
            public void onTokenIncorrect() {
                Log.e("LoginActivity", "onTokenIncorrect");
                YcToastHelper.getInstance()._toast("对不起,token错误");
            }

            @Override
            public void onSuccess(String userid) {
                LoadDialog.dismiss(act);
                Log.e("LoginActivity", "连接融云IM成功,userid=" + userid);
                IntentHelper.getInstances().getIntent(act, MainActivity.class);
                IntentHelper.finish(act);
//                sendMsg();
            }

            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {
                Log.e("LoginActivity", "ErrorCode");
                YcToastHelper.getInstance()._toast("对不起,连接失败!" + String.valueOf(errorCode));
            }

        });

    }
}
